<?php

namespace App\Http\Controllers\www;

use App\Http\Controllers\Weixin\WeixinServiceController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Models\V1\Active666Model;
use EasyWeChat\Payment\Order;
use App\Models\V1\RegionModel;
use Intervention\Image\Facades\Image;
use App\Models\V1\OrderProcessTemplateModel;
use App\Jobs\BaiduYuyin666Job;
use App\Common\Http;



class Zhongchou666Controller extends Controller
{

    public $managerId = 0;
    public $moneys    =  [9,19,39,69];
    /**
     * 本控制器的入口
     * */
    public function enter(Request $request)
    {
        $this->managerId  = $request->input('managerId',0);
        $fun    = $request->input('fun','index');
        return $this->$fun($request);
    }


    /**
     * 发起众筹的首页
     *
     * */
    public function index(Request $request)
    {
        $wxInfo     = $this->wx_login($request);
        if (!is_array($wxInfo)) {
            return $wxInfo;
        }
        $activityId = $request->input('activityId');
        $zcModel    = new Active666Model();
        $activity   = $zcModel->get_activity_info($activityId);

        //绑定为发起人
        if($request->input('bind') && !self::is_manager($activity->openids, $wxInfo['openid'])) {
            $ids = $activity->openids ? $activity->openids . ',' : '';
            $ids .= $wxInfo['openid'];
            DB::table('666_activity')->where('activity_id', $activityId)->update(['openids' => $ids]);
        }

        //获取所有的人
        $orders     = $this->getTypeOrders($activity->type_id);

        // $orders     = $this->get_activity_orders($activityId);
        $ordersArr  = array_chunk($orders, 6);

        $weixinController = new WeixinServiceController();
        $weixinApp  = $weixinController->get_weixin_app();
        $weixinJs   = $weixinApp->js;
        $subplusTime= self::getSubplusTime($activity->end_time);

        // 支持人数
        $supportsNum = DB::table('666_order_pay_log')->where('id', '>', 17465)->where('pay_status', 1)->distinct('open_id')->count();

        $data       = [
            'weixinJs'  => $weixinJs,
            'activity'  => $activity,
            'orders'    => $orders,
            'ordersArr' => $ordersArr,
            'subTime'   => $subplusTime,
            'files'     => self::getFiles(),
            'userInfo'  => $wxInfo,
            'supports'  => $supportsNum
        ];
        return view('www/zc-666/index',$data);
    }

    public function bind_manager(Request $request) {
        $activityId = $request->input('activityId');
        $openid = $request->input('openid');
        DB::table('666_activity')->where('activity_id',$activityId)->update(['openid' => $openid]);
        return apiData()->send();
    }

    public function manage(Request $request) {

        $wxInfo     = $this->wx_login($request);
        if (!is_array($wxInfo)) {
            return $wxInfo;
        }

        $zcModel    = new Active666Model();
        $activity   = $zcModel->get_activity_info(0, $wxInfo['openid']);

        if (!$activity) {
            return view('/www/zc-666/error', ['msg' => '您还不是活动发起人']);
        }

        //检查是否有用户的订单

        //获取所有的人
        $orders     = $this->get_activity_orders($activity->activity_id);
        $ordersArr  = array_chunk($orders, 6);

        $weixinController = new WeixinServiceController();
        $weixinApp  = $weixinController->get_weixin_app();
        $weixinJs   = $weixinApp->js;
        $subplusTime= self::getSubplusTime($activity->end_time);

        $data       = [
            'weixinJs'  => $weixinJs,
            'activity'  => $activity,
            'orders'    => $orders,
            'ordersArr' => $ordersArr,
            'subTime'   => $subplusTime,
            'files'     => self::getFiles(),
            'userInfo'  => $wxInfo
        ];
        return view('www/zc-666/manage',$data);
    }

    /**
     * 用户众筹的页面
     * */
    public function register(Request $request)
    {
        $activityId     = $request->input('activityId');
        $orderId        = $request->input('orderId');
        $wxInfo         = $this->wx_login($request);
        $regionModel    = new RegionModel();
        $countrys       = $regionModel->get_countries();
        $activityModel  = new Active666Model();

        //$orderInfo  = $activityModel->get_user_order($wxInfo['openid'],$activityId);
        $activityInfo   = $activityModel->get_activity_info($activityId);
        $typeId     = $activityInfo->type_id;
        $orderInfo  = DB::table("666_order as a")
            ->leftJoin('666_activity as b','b.activity_id','=','a.activity_id')
            ->select('a.*')
            ->where('a.open_id',$wxInfo['openid'])
            ->where('b.type_id','=',$typeId)
            ->where('a.deleted_at')
            ->where('b.delete_at')
            ->first();

        if($orderInfo)
        {
            return response()->redirectTo('www/zhongchou666/order?orderId='.$orderInfo->id);
        }



        $weixinController = new WeixinServiceController();
        $weixinApp  = $weixinController->get_weixin_app();
        $weixinJs   = $weixinApp->js;

        $data           = [
            'activityId'    => $activityId,
            'orderId'       => $orderId,
            'activity'      => $activityInfo,
            'weixinJs'      => $weixinJs,
            'countrys'      => $countrys
        ];
        return view('www/zc-666/register',$data);
    }



    /**
     * 处理提交众筹的订单
     *
     * */
    public function register_action(Request $request)
    {
        $wxInfo     =   $this->wx_login($request);
        $orderId    =   $request->input('orderId');
        $activityId =   $request->input('activityId');
        $orderModel =   new Active666Model();
        $orderInfo  =   $orderModel->get_order_info($orderId);
        $idTree     =   $orderInfo ? $orderInfo->id_tree."," : "";


        //检查改用户是否已经有了订单
        $hasOrder = $orderModel->get_user_order($wxInfo['openid'],$activityId);
        if($hasOrder)
        {
            $url     = "/www/zhongchou666/order?orderId=".$hasOrder->id;
            return "<script>location.replace('{$url}')</script>";
        }

        $data   = [
            'real_name'     => $request->input('name',''),
            'mobile'        => $request->input('mobile'),
            'school'        => $request->input('school',''),
            'manager_id'    => $request->input('managerId',0),
            'face_img'      => "",
            'parent_id'     => $orderId,
            'open_id'       => $wxInfo['openid'],
            'wx_name'       => $wxInfo['nickname'],
            'wx_head'       => self::copy_img($wxInfo['headimgurl'], $wxInfo['openid']),
            // 'union_id'      => $wxInfo['unionid'],
            'activity_id'   => $activityId,
            'created_at'    => date_time(),
        ];


        $id = DB::table('666_order')->insertGetId($data);

        $idTrees    = explode(",", $idTree);
        //更改所有父级订单的订单数据
        foreach($idTrees as $oid)
        {
            DB::table('666_order')->where('id',$oid)->increment('child_num');
        }


        //给发起人添加数量
        DB::table('666_activity')->where('activity_id',$activityId)->increment('order_total_num');

        //更改IDtree
        $idTree     = $idTree.$id;
        $orderModel->update_order_info($id,['id_tree'=>$idTree]);

        if(0)
        {
             //判断用户是否关注公众号
            $weixinService  = new WeixinServiceController();
            $isSubscribe    = $weixinService->isSubscribe($wxInfo['openid']);

            //如果没有关注公众号 则跳转到关注的界面
            if($isSubscribe == false)
            {
                $app        = $weixinService->get_weixin_app();
                $key        = 1000000 + $id;
                $resultInfo = $app->qrcode->temporary($key,3600);
                $imgUrl     = $app->qrcode->url($resultInfo['ticket']);
                return view('www/zc-666/wx-subscribe',['qrImg'=>$imgUrl]);
            }
        }
       
        $url     = "/www/zhongchou666/order?orderId=".$id;
        $content = "<script>location.replace('{$url}')</script>";
        return $content;
    }

  
    /**
     * 微信关注
     * */
    public function wx_subscribe(Request $request)
    {
        return view('www/zc-666/wx-subscribe');
    }

    public function order(Request $request)
    {
        $wxInfo     = $this->wx_login($request);
        $orderId    = $request->input('orderId');
        $orderModel = new Active666Model();
        $orderInfo  = $orderModel->get_order_info($orderId);
        $orderInfo->surplusTime = strtotime($orderInfo->created_at) + ($orderInfo->days * 24 * 60 *60) -time();
        $supports   = $orderModel->get_order_supporter($orderId);
        $activityInfo= $orderModel->get_activity_info($orderInfo->activity_id);

        $total      = 0;
        // return $_SERVER;
        //计算完成的比例
        foreach($supports as $sup)
        {
            $sup->created_at    = str_replace('-','/',$sup->created_at);
            $total              += $sup->pay_money;
            $sup->message       = emoji_text_decode($sup->message);

            //获得评论
            $comments       = DB::table('666_comment')->where('pay_log_id',$sup->id)->get();
            foreach($comments as $com)
            {
                $com->content = emoji_text_decode($com->content);
            }
            $sup->comments  = $comments;

        }

        $percent    = intval($total/$activityInfo->money *100);
        $percent    = $percent > 100 ? 100 : $percent;


        $weixinController = new WeixinServiceController();
        $weixinApp  = $weixinController->get_weixin_app();
        $weixinJs   = $weixinApp->js;

        $needMoney  = $activityInfo->money  - $total;


        $moneys     =  [0.01,11,33,66,99];

        //获取所有的人

        $orders     = $this->get_activity_orders($orderInfo->activity_id,$orderId);


        $childOrders= $this->get_child_orders($orderId,$activityInfo->money);
        $surplusMoney   = bcsub($activityInfo->money,$orderInfo->raised_money,2);// - number_format(,2);

        if($surplusMoney<0)
        {
            $surplusMoney = 0;
        }
        $orderInfo->surplusMoney    = $surplusMoney;
        $endDay = strtotime($orderInfo->created_at) + $orderInfo->days * 24 * 60 * 60;
        $subPlusTime = self::getSubplusTime($endDay);
        $isManager = self::is_manager($activityInfo->openids, $wxInfo['openid']);
        return view('www/zc-666/order',[
            'orderInfo'     => $orderInfo,
            'supports'      => $supports,
            'percent'       => $percent,
            'weixinJs'      => $weixinJs,
            'totalMoney'    => $activityInfo->money,
            'userInfo'      => $wxInfo,
            'moneys'        => $moneys,
            'activity'      => $activityInfo,
            'orders'        => $orders,
            'childOrders'   => $childOrders,
            'subTime'       => $subPlusTime,
            'selfOrder'     => $orderInfo->open_id == $wxInfo['openid'],
            'isManager'     => $isManager,
            'files'     => self::getFiles()
            ]);
    }


    public function messages(Request $request) {
        $wxInfo     = $this->wx_login($request);
        $orderId    = $request->input('orderId');
        $orderModel = new Active666Model();
        $orderInfo  = $orderModel->get_order_info($orderId);
        $orderInfo->surplusTime = strtotime($orderInfo->created_at) + ($orderInfo->days * 24 * 60 *60) -time();
        $supports   = $orderModel->get_order_supporter($orderId);
        $activityInfo= $orderModel->get_activity_info($orderInfo->activity_id);
        $total      = 0;

        //计算完成的比例
        foreach($supports as $sup)
        {
            $sup->created_at    = str_replace('-','/',$sup->created_at);
            $total              += $sup->pay_money;
            $sup->message       = emoji_text_decode($sup->message);

            //获得评论
            $comments       = DB::table('666_comment')->where('pay_log_id',$sup->id)->get();
            foreach($comments as $com)
            {
                $com->content = emoji_text_decode($com->content);
            }
            $sup->comments  = $comments;

        }

        $weixinController = new WeixinServiceController();
        $weixinApp  = $weixinController->get_weixin_app();
        $weixinJs   = $weixinApp->js;


        $surplusDay     = $orderInfo->days - intval( (time() - strtotime($orderInfo->created_at)) / (24 * 60 * 60));
        $surplusDay     = $surplusDay < 0 ? 0 : $surplusDay;
        $orderInfo->surplusDay      = $surplusDay;

        return view('www/zc-666/messages',[
            'orderInfo'     => $orderInfo,
            'supports'      => $supports,
            'weixinJs'      => $weixinJs,
            'userInfo'      => $wxInfo,
            'activity'      => $activityInfo,
        ]);
    }

    //获取微信信息
    public function wx_login(Request $request)
    {

        if(!is_online()){
            $wxInfo =   [
                'openid'    => 'oPF8hxOdJ6B-HJHNgb-3U3KQ6rUA',
                'nickname'  => '张维喜',
                'headimgurl'=> 'http://www.18183.com/uploads/allimg/140616/61-140616111040.jpg',
                'unionid'   => 'dkdkkckkdsowo',
            ];
            return $wxInfo;
        }

        $wxService  = new WeixinServiceController();
        $userInfo   = $wxService->userinfo($request);
        if (!is_array($userInfo)) {
            return $userInfo;
        }
        return $userInfo['original'];
    }

    public function get_activity_orders($activityId,$parentId=0)
    {
        //获取所有的人
        $model          = new Active666Model();
        $activityInfo   = $model->get_activity_info($activityId);
        $totalMoney     = $activityInfo->money;
        $orders     = DB::table('666_order')
            ->where('activity_id',$activityId)
            ->where('deleted_at')
            ->select("wx_head",'raised_money','id','raised_money');
        if($parentId > 0)
        {
            $orders->where('parent_id',"<>",$parentId);

        }
        $orders = $orders->orderBy('raised_money','desc')->get()->toArray();
        foreach($orders as $order)
        {
            $order->percent = $order->raised_money / $totalMoney * 100;
            $order->percent = intval($order->percent > 100 ? 100 : $order->percent);

        }
        return $orders;
    }


    public function getTypeOrders($typeId) {
        $model          = new Active666Model();
        $activityIds    = DB::table('666_activity')->where('type_id', $typeId)->pluck('activity_id');
        $activityInfo   = DB::table('666_activity')->where('type_id', $typeId)->first();
        $totalMoney     = $activityInfo->money;
        $orders     = DB::table('666_order')
            ->whereIn('activity_id',$activityIds)
            ->where('deleted_at')
            ->select("wx_head",'raised_money','id','raised_money');

//        if($parentId > 0)
//        {
//            $orders->where('parent_id',"<>",$parentId);
//
//        }
        $orders = $orders->orderBy('raised_money','desc')->get()->toArray();
        foreach($orders as $order)
        {
            $order->percent = $order->raised_money / $totalMoney * 100;
            $order->percent = intval($order->percent > 100 ? 100 : $order->percent);

        }
        return $orders;
    }

    public function get_child_orders($orderId,$totalMoney)
    {
        //获取所有的人
        $orders     = DB::table('666_order')
            ->where('parent_id',$orderId)
            ->select("wx_head",'raised_money','id')
            ->get()->toArray();


        foreach($orders as $order)
        {
            $order->percent = $order->raised_money / $totalMoney * 100;
            $order->percent = intval($order->percent > 100 ? 100 : $order->percent);

        }

        return $orders;
    }

    //获得支付的数据
    public function get_pay_data(Request $request)
    {

        $orderModel = new Active666Model();
        $url        = $request->input('url');
        $orderId    = $request->input('orderId');
        $money      = $request->input('money');
        $mobile     = $request->input('mobile','');
        $name       = $request->input('name','');
        $isAnonymous= $request->input('isAnonymous');
        $msg        = $request->input('msg');
        $msg        = $msg ? $msg : '撸起袖子加油干，支持你！';
        $orderInfo  = $orderModel->get_order_info($orderId);

        $actInfo    = $orderModel->get_activity_info($orderInfo->activity_id);
        $totalMoney = $actInfo->money;

        //检查金额
        $money     = floatval($money);
        $money     = number_format($money,2);
        if($money < 0.01)
        {
            return apiData()->send(4001,'金额不能小于0.01');
        }


        if(intval($orderInfo->raised_money + $money) > $totalMoney )
        {
            $money = intval($totalMoney - $orderInfo->raised_money);
            return apiData()->send(4003,"只需要".$money."元就筹满了");
        }

        $wxInfo     = $this->wx_login($request);
        define('CURRENT_URL',$url);
        $wxService  = new WeixinServiceController();
        $app        = $wxService->get_weixin_app();
        $payment    = $app->payment;

        $tradeNo    = create_member_number();
        $callbackUrl= url('www/zhongchou666/wx_pay_callback');

        $attributes = [
            'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
            'body'             => "给{$orderInfo->wx_name}的筹资",
            'detail'           => 'xxxxx',
            'out_trade_no'     => $tradeNo,
            'total_fee'        => $money*100, // 单位：分
            'notify_url'       => $callbackUrl, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $wxInfo['openid'], // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
            // ...
        ];
        $order = new Order($attributes);

        //生成一个支付下单记录

        $data   = [
            'order_id'  => $orderId,
            'open_id'   => $wxInfo['openid'],
            'union_id'  => '', //$wxInfo['unionid'],
            'wx_name'   => $wxInfo['nickname'],
            'wx_head'   => self::copy_img($wxInfo['headimgurl'], $wxInfo['openid']),
            'name'      => $name,
            'mobile'    => $mobile,
            'out_trade_no'=>$tradeNo,
            'pay_money' => $money,
            'pay_status'=> 0,
            'created_at'=> date_time(),
            'message'   => emoji_text_encode($msg),
            'is_annoymous'=>$isAnonymous
        ];
        $payLogId   = $orderModel->add_pay_log($data);

        //$result = $payment->pay($order);
        $result = $payment->prepare($order);

        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS')
        {
            $prepayId = $result->prepay_id;
        }
        else
        {
            return apiData()->send(4001,'下单失败');
        }
        $jsConfig   = $payment->configForPayment($prepayId);
        $jsConfig   = \GuzzleHttp\json_decode($jsConfig);
        return apiData()->set_data('jsConfig',$jsConfig)
            ->set_data('payLogId',$payLogId)
            ->set_data('url',$callbackUrl)
            ->send(200,'ok');
    }


    public function yanshi(Request $request)
    {
        $orderId    = $request->input('orderId');
        $weixinInfo = $this->wx_login($request);
        $openId     = $weixinInfo['openid'];

        $result     = DB::table('666_order')->where('id',$orderId)->where('open_id',$openId)->increment('days',30);
        if(!$result)
        {
            return apiData()->send(2001,'操作失败');
        }
        return apiData()->send(200,'已延长30天时间');
    }


    /**
     * 微信支付回调
     * */
    public function wx_pay_callback(Request $request)
    {
        $weixinService  = new WeixinServiceController();
        $app            = $weixinService->get_weixin_app();
        $GLOBALS['wxservice']   = $weixinService;

        $response = $app->payment->handleNotify(function($notify, $successful){
            // 你的逻辑
            $dateTime   = date_time();
            $tradeNo    = $notify->out_trade_no;
            $payLogINfo = DB::table('666_order_pay_log')
                ->where('out_trade_no',$tradeNo)
                ->first();

            if($payLogINfo->pay_status == 1)
            {
                return true;
            }

            DB::table('666_order_pay_log')
                ->where('id',$payLogINfo->id)
                ->update(['pay_status'=>1,'pay_time'=>$dateTime]);
            //检查本订单知否筹完
            $orderInfo  = DB::table('666_order')
                ->where('id',$payLogINfo->order_id)
                ->first();
            $raisedMoney    = $orderInfo->raised_money + $payLogINfo->pay_money;
            $minMoney       = system_log('666_min_money');
            $newOrderInfo   = [
                'raised_money'=> $raisedMoney,
                'supports_num'=> $orderInfo->supports_num + 1
            ];

            DB::table('666_activity')->where('activity_id',$orderInfo->activity_id)->increment('supports_num');

            $orderStatus    = "众筹中";
            if($raisedMoney >= $minMoney)
            {
                $newOrderInfo['success_time'] = $dateTime;
                $orderStatus = "众筹完成";

                //增加活动完成的数量
                DB::table('666_activity')->where('activity_id',$orderInfo->activity_id)->increment('order_finish_num');
            }

            DB::table('666_order')->where('id',$payLogINfo->order_id)->update($newOrderInfo);
            if($payLogINfo->is_annoymous == 0){
                $name   = $payLogINfo->wx_name;
            }else{
                $name   = "一个朋友匿名";
            }
            if($GLOBALS['wxservice']->isSubscribe($orderInfo->open_id) == false){

                return true;
            }
            //给发起人发送通知
            $data   = new OrderProcessTemplateModel();
            $data->openId       = $orderInfo->open_id;
            $data->orderInfo    = '朋友支持众筹推送信息';
            $data->orderSn      = $orderInfo->id;
            $data->orderStatus  = $orderStatus;
            $data->otherInfo    = $name."帮你筹集了".$payLogINfo->pay_money."元,总计已筹".$raisedMoney."元";
            $data->orderTime    = $dateTime;
            $data->orderType    = "来自朋友的关心";
            $data->url          = url('www/zhongchou666/enter?fun=order&orderId='.$orderInfo->id);
            $GLOBALS['wxservice']->send_order_process_template($data);
            return true; // 或者错误消息
        });
        return $response; // Laravel 里请使用：return $response;
    }


    public function send_first_order($orderId)
    {

        $model      = new Active666Model();
        $orderInfo  = $model->get_order_info($orderId);
        //给发起人发送通知
        $data   = new OrderProcessTemplateModel();
        $data->openId       = $orderInfo->open_id;
        $data->orderInfo    = '众筹信息';
        $data->orderSn      = $orderInfo->id;
        $data->orderStatus  = "等待众筹";
        $data->otherInfo    = "点击进入页面分享给朋友，让他们来给你助力";
        $data->orderTime    = $orderInfo->created_at;
        $data->orderType    = "我的众筹";
        $data->url          = url('www/zhongchou666/enter?fun=order&orderId='.$orderInfo->id);
        $GLOBALS['wxservice']->send_order_process_template($data);
    }

    /**
     * 分享接听手机的页面
     * */
    public function share_mobile(Request $request)
    {
        $wxInfo     = $this->wx_login($request);
        $orderId    = $request->input('orderId');
        $orderModel = new Active666Model();
        $orderInfo  = $orderModel->get_order_info($orderId);

        $weixinService  = new WeixinServiceController();
        $app            = $weixinService->get_weixin_app();
        $weixinJs       = $app->js;

        return view('www/zc-666/mobile',[
            'orderInfo'=>$orderInfo,
            'userInfo' => $wxInfo,
            'weixinJs'=>$weixinJs]);
    }

    /**
     * 众筹订单列表
     * */
    public function order_list(Request $request)
    {
        return view('www/zc-666/order-list');
    }

    /**
     * 分页订单显示
     * */
    public function page_orders(Request $request)
    {
        $managerId  = $request->input('managerId',0);
        $isSuccess  = $request->input('isSuccess',-1);
        $page       = $request->input('page',1);
        $orderModel = new Active666Model();
        $orders     = $orderModel->get_orders($managerId,$isSuccess);
        foreach($orders as $k=>$order){
            if($page == 1 && $k < 3){
                $order->sort = $k+1;
            }else{
                $order->sort = 0;
            }
        }
        return apiData()->set_data('orders',$orders)->send(200,'ok');
    }


    /**
     * 添加订单评论
     * */
    public function add_order_comment(Request $request)
    {
        $comment    = $request->input('comment');
        $payId      = $request->input('payId');
        $wxInfo     = $this->wx_login($request);

        $data       = [
            'content'   => emoji_text_encode($comment),
            'pay_log_id'=> $payId,
            'wx_name'   => $wxInfo['nickname'],
            'wx_head'   => self::copy_img($wxInfo['headimgurl'], $wxInfo['openid'])
        ];
        DB::table('666_comment')->insert($data);

        return apiData()->set_data('comment',$data)->send(200,'ok');
    }


    /**
     * 支付界面
     * */
    public function pay_page(Request $request){

        $orderId    = $request->input('orderId');
        $orderModel = new Active666Model();
        $orderInfo  = $orderModel->get_order_info($orderId);
        $activityInfo= $orderModel->get_activity_info($orderInfo->activity_id);
        $weixinController = new WeixinServiceController();
        $weixinApp  = $weixinController->get_weixin_app();
        $weixinJs   = $weixinApp->js;
        $wxinfo     = $this->wx_login($request);
        $mobileInfo = DB::table('666_order_pay_log')
            ->where('open_id',$wxinfo['openid'])
            ->where('mobile',"<>","")
            ->where('name',"<>","")
            ->orderBy('id','desc')
            ->first();

        if(!$mobileInfo)
        {
            $mobileInfo = new \stdClass();
            $mobileInfo->mobile = "";
            $mobileInfo->name   = "";
        }

        $data       = [
            'moneys'    => $this->moneys,
            'orderId'   => $orderId,
            'activity'  => $activityInfo,
            'weixinJs'      => $weixinJs,
            'mobileInfo'    => $mobileInfo
        ];
        return view('www/zc-666/pay-page',$data);
    }


















    /*===============管理员  begin ===================*/

    /**
     * 后台登录页面
     * */
    public function admin_login(Request $request)
    {
        $managerInfo    = $request->session()->get('managerInfo');
        if($managerInfo){
            return $this->admin_orders($request);
        }
        $weixinInfo = $this->wx_login($request);
        //判断管理员是否绑定过
        $openId         = $weixinInfo['openid'];
        $model          = new Active666Model();
        $managerInfo    = $model->get_manager_info_by_openid($openId);
        if($managerInfo)
        {
            $request->session()->put('managerInfo',$managerInfo);
            $request->session()->save();
            $url    = url('www/zhongchou666/enter?fun=admin_orders');
            return response()->redirectTo($url);
        }
        return view('www/zc-666/admin-login');
    }



    /**
     * 后台登录操作
     * */
    public function admin_login_action(Request $request)
    {

        $password   = md5($request->input('password'));
        $mobile     = $request->input('mobile');
        $orderModel = new Active666Model();
        $managerInfo= $orderModel->get_manager_info_by_mobile($mobile);
        if(!$managerInfo) {

            return apiData()->notice('账户不存在');
        }
        elseif($managerInfo->password != $password){

            return apiData()->notice('账户或密码错误');

        }else{//绑定微信

            $wxInfo = $this->wx_login($request);
            if(empty($managerInfo->open_id)){
                $data   = [
                    'open_id'   => $wxInfo['openid'],
                    'union_id'  => $wxInfo['unionid'],
                    'wx_name'   => $wxInfo['nickname'],
                    'wx_head'   => $wxInfo['headimgurl']
                ];
                $orderModel->update_manager($managerInfo->id,$data);
                $managerInfo    = $orderModel->get_manager_info($managerInfo->id);
            }
        }

        $request->session()->put('managerInfo',$managerInfo);
        $request->session()->save();
        $url    = url('www/zhongchou666/enter?fun=admin_orders');
        return response()->redirectTo($url);
    }


    /**
     * 后台订单列表
     * */
    public function admin_orders(Request $request)
    {

        $orderModel     = new Active666Model();
        $managerId      = $request->session()->get('managerInfo')->id;

        $isSuccess      = $request->input('isSuccess',-1);
        $orders         = $orderModel->get_orders($managerId,$isSuccess);

        //1总订单
        //2.已完成订单
        //3.进行中订单
        $totalNum       = $orderModel->count_order($managerId,-1);
        $finishedNum    = $orderModel->count_order($managerId,1);
        $unFinishedNum  = $orderModel->count_order($managerId,0);

        $endTime        = system_log('666_end_time');
        $time           = strtotime($endTime) - time();
        $day            = floor($time / (24 * 60 *60));
        $hour           = floor($time % (24*60*60) / (60*60));
        $min            = floor($time % (60*60) / 60) ;
        $time           = $day."天".$hour."小时".$min."分钟";


        foreach($orders as $order)
        {
            if($order->success_time){
                $useTime = strtotime($order->success_time) - strtotime($order->created_at);
                //$order->useTime = $useTime;
                $order->useTime = floor($useTime/(60*60)) ."小时".floor(($useTime % (60*60)) / 60)."分钟完成" ;
            }else{
                $order->useTime = "未完成";
            }

        }

        return view('www/zc-666/admin-orders',[
            'orders'        => $orders,
            'isSuccess'     => $isSuccess,
            'managerId'     => $managerId,
            'totalNum'      => $totalNum,
            'finishedNum'   => $finishedNum,
            'unFinishedNum' => $unFinishedNum,
            'time'          => $time
        ]);
    }

    private static function copy_img($srcImg, $openid) {
        $distImg = "/www/zc666/wximgs/{$openid}.jpg";
        $distImgPath = public_path(trim($distImg, '/'));
        if (file_exists($distImgPath)) {
            return $distImg;
        }
        $data = file_get_contents($srcImg);
        file_put_contents($distImgPath, $data);
        return $distImg;
    }

    private static function getSubplusTime($endTime) {
        if(is_string($endTime)) {
            $endTime = strtotime($endTime);
        }
        $time = $endTime - time();
        $time = $time >=0 ? $time : 0;
        $dtime = 24*60*60;
        $htime = 60*60;
        $mtime = 60;

        return [
            (int) ($time / $dtime),
            (int) (($time % $dtime) / $htime),
            (int) (($time % $htime) / $mtime),
            $time % $mtime
        ];
    }
    private static function getFiles() {
        $pad = 'www/zc666/web/img-ad';
        $pbm = 'www/zc666/web/img-bm';
        $pxm = 'www/zc666/web/img-xm';
        $pzz = 'www/zc666/web/img-zz';

        $ads = scandir(public_path($pad));
        $bms = scandir(public_path($pbm));
        $xms = scandir(public_path($pxm));
        $zzs = scandir(public_path($pzz));
        array_splice($ads, 0, 2);
        array_splice($bms, 0, 2);
        array_splice($xms, 0, 2);
        array_splice($zzs, 0, 2);

        usort($ads, function($a, $b) {return strnatcasecmp(basename($a), basename($b));});
        usort($bms, function($a, $b) {return strnatcasecmp(basename($a), basename($b));});
        usort($xms, function($a, $b) {return strnatcasecmp(basename($a), basename($b));});
        usort($zzs, function($a, $b) {return strnatcasecmp(basename($a), basename($b));});

        foreach ($ads as $i => $v) { $ads[$i] = $pad . '/' . $v;}
        foreach ($bms as $i => $v) { $bms[$i] = $pbm . '/' . $v;}
        foreach ($xms as $i => $v) { $xms[$i] = $pxm . '/' . $v;}
        foreach ($zzs as $i => $v) { $zzs[$i] = $pzz . '/' . $v;}
        return [
            'ad' => $ads,
            'bm' => $bms,
            'xm' => $xms,
            'zz' => $zzs
        ];
    }

    private static function is_manager($ids, $id) {
        if ($ids) {
            $ids = explode(',', $ids);
        } else {
            $ids = [];
        }

        return in_array($id, $ids);
    }
}
